import {Component, HostListener} from '@angular/core';
import {HomeService} from "../providers/service/home.service";
import {Router} from "@angular/router";

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html'
})


export class HomeComponent  {
    flag: boolean;//控制滚动翻页

    constructor(public homeService: HomeService,
                private router: Router,

    ) {

        this.flag = false;
    }

    ngOnInit() {
        //滚动条高度
        if(this.homeService.scrollTop==0){
            this.getArticleRecommend();
        }

    }

    ngAfterViewInit(){
        document.documentElement.scrollTop=this.homeService.scrollTop;
    }





    //推荐文章
    getArticleRecommend() {
        this.homeService.getArticleRecommend({page: this.homeService.articleRecommend.current_page, search: this.homeService.search})
            .subscribe(data => {
                if (data.status_code == 200) {
                    this.homeService.articleRecommend = data.result;

                    if(this.homeService.search){
                        //清空list
                        this.homeService.list=[];
                    }
                    //将数据追加到尾部
                    for (let v of data.result.data) {
                        this.homeService.list.push(v);
                    }

                    if (this.homeService.page.length < 1) {
                        for (let i = 1; i <= this.homeService.articleRecommend.last_page; i++) {
                            this.homeService.page.push(i);
                        }
                    }
                }
            });
    }


    //翻页
    changePage() {
        this.homeService.articleRecommend.current_page++;
        this.getArticleRecommend();

    }

    //监听滚动，加载数据
    @HostListener('window:scroll', ['$event']) public onScroll = ($event) => {

        //客户端高度
        var clientH = document.documentElement.clientHeight;
        //body高度
        var bodyH = document.body.clientHeight;

        //滚动的高度
        var scrollTop = document.documentElement.scrollTop;


        //滚动到底部60以内
        if (bodyH - clientH - scrollTop < 80) {
            if (!this.flag) {
                //翻页
                this.changePage();
            }
            this.flag = true;
        } else {
            this.flag = false;
        }
    }

    //搜索文章
    searchArticle(){
        //没有值，不搜索
        if(!this.homeService.search)return;
        //搜索，将当前分页置1
        this.homeService.articleRecommend.current_page=1;
        this.getArticleRecommend();

    }



}
